import axios from 'axios'

const service = axios.create({
  baseURL: 'http://localhost:3000', // 本地mock服务地址
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器
service.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response.status === 404) {
      router.push('/404')
    }
    return Promise.reject(error)
  }
)

service.get = async function(url, config = {}) {
  if (config.fullResponse) {
    const res = await axios.get(url, { ...config, baseURL: service.defaults.baseURL })
    return res
  } else {
    return service.request({ url, method: 'get', ...config })
  }
}

export default service  